package com.hss01248.dialog;

import com.hss01248.dialog.comp.AlertDialog;
import com.hss01248.dialog.comp.CustomDialog;
import com.hss01248.dialog.ios.IosAlertDialogHolder;
import com.hss01248.dialog.material.MdInputHolder;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.service.*;
import ohos.app.AbilityContext;
import ohos.app.Context;
import ohos.agp.components.Text.TextSizeType;
import ohos.eventhandler.EventHandler;


import com.hss01248.dialog.adapter.SuperLvHolder;
import com.hss01248.dialog.config.ConfigBean;
import com.hss01248.dialog.config.DefaultConfig;
import com.hss01248.dialog.view.DialogUtil_DialogActivity;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by Administrator on 2016/10/9 0009.
 */
public class Tool {

    public static void dismiss(ConfigBean bean,boolean isAfterResult){
        if(isAfterResult && !bean.dismissAfterResultCallback){
            return;
        }

        //先隐藏keyboard
        hideKeyBorad(bean);
        if(bean.showAsActivity){
            Ability activity = ActivityStackManager.getInstance().getTopActivity(DialogUtil_DialogActivity.class);
            if(activity!=null){
                activity.terminateAbility();
            }
            return;
        }
        if(bean.dialog!=null){
            bean.dialog.destroy();
        }
        if(bean.alertDialog !=null){
            bean.alertDialog.destroy();
        }
    }

    public static void dismiss(ConfigBean bean){
        dismiss(bean,false);
    }


    public static EventHandler getMainHandler() {
        if (mainHandler == null) {
            mainHandler = new EventHandler(EventRunner.getMainEventRunner());
        }
        return mainHandler;
    }
    private static EventHandler mainHandler;

    /**
     * 解决badtoken问题,一劳永逸
     * @param dialog
     */
    public static void showDialog(final CommonDialog dialog, final ConfigBean bean) {
        StyledDialog.getMainHandler().postTask(new Runnable() {
                @Override
                public void run() {
                    try {
                        adjustWindow(dialog,bean);
                        dialog.show();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
    }


    public static void setListener(final CommonDialog dialog, final ConfigBean bean) {
        if(dialog ==null){
            return;
        }

        dialog.registerDisplayCallback(new BaseDialog.DisplayCallback() {
            @Override
            public void onDisplay(IDialog dialog) {
                if (bean.alertDialog!= null){
                    setMdBtnStytle(bean);
                }
                bean.listener.onShow();
                DialogsMaintainer.addWhenShow(bean.context, (CommonDialog)dialog);
                if (bean.type == DefaultConfig.TYPE_IOS_LOADING || bean.type == DefaultConfig.TYPE_MD_LOADING) {
                    DialogsMaintainer.addLoadingDialog(bean.context, (CommonDialog)dialog);
                }
            }
        });

        dialog.registerRemoveCallback(new BaseDialog.RemoveCallback() {
            @Override
            public void onRemove(IDialog dialog0) {
                if(bean.type == DefaultConfig.TYPE_IOS_INPUT){
                    IosAlertDialogHolder iosAlertDialogHolder = (IosAlertDialogHolder) bean.viewHolder;
                    if(iosAlertDialogHolder!=null){
                        iosAlertDialogHolder.hideKeyBoard();
                    }
                }
                if(bean.listener!=null) {
                    bean.listener.onCancle();
                }
            }
        });

        dialog.setDestroyedListener(new CommonDialog.DestroyedListener() {
            @Override
            public void onDestroy() {
                if(bean.listener !=null){
                    bean.listener.onDismiss();
                }
                DialogsMaintainer.removeWhenDismiss(dialog);
                if (bean.type == DefaultConfig.TYPE_IOS_LOADING || bean.type == DefaultConfig.TYPE_MD_LOADING) {
                    DialogsMaintainer.dismissLoading(dialog);

                }
            }
        });
    }

    private static void adjustWindow(final CommonDialog dialog, final ConfigBean bean) {
        if (dialog.getContentCustomComponent()!= null) {
            ComponentContainer cc = (ComponentContainer)dialog.getContentCustomComponent();
            cc.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() {
                @Override
                public void onRefreshed(Component component) {
                    adjustWH(dialog, bean);
                }
            });
        }
    }

    public static void setWindowAnimation(Window window, ConfigBean bean) {
        int gravity = bean.gravity;
        if(gravity == LayoutAlignment.BOTTOM || gravity == (LayoutAlignment.BOTTOM | LayoutAlignment.HORIZONTAL_CENTER)){
            //window.setWindowAnimations(R.style.ani_bottom);
            // TODO windows not have Animation function
            //Animator animator = AnimatorScatter.getInstance(bean.context).parse(0);//R.style.ani_bottom
            //animator.start();
            
        }else if(gravity == LayoutAlignment.CENTER){
            //window.setWindowAnimations(R.style.dialog_center);
        }
    }



    public static void runOnUIThread(Runnable runnable){
        getMainHandler().postTask(runnable);
    }

    public static void runOnUIThreadDelayed(Runnable runnable){
        getMainHandler().postTask(runnable, 500);
    }

    public static void showSoftKeyBoardDelayed(boolean sholudShouldKeyBoard,final SuperLvHolder holder){
        if(!sholudShouldKeyBoard){
            return;
        }
        if(holder ==null){
            return;
        }
        holder.showKeyBoard();
    }


    /**
     * 必须在show之后,button才不会返回null
     * @param bean
     */
    public static void setMdBtnStytle(final ConfigBean bean){
        Button btnPositive =
                bean.alertDialog.getPositiveButton();
        Button btnNegative =
                bean.alertDialog.getNegativeButton();
        Button btnNatural =
                bean.alertDialog.getNeutralButton();

        if(btnPositive !=null){
            if(!Tool.isEmpty(bean.text1)){
                btnPositive.setText(bean.text1.toString());
            }
            if (bean.btn1Color > 0){
                setTextColorById(btnPositive, bean.btn1Color);
            }

            if(bean.btnTxtSize >0){
                btnPositive.setTextSize(bean.btnTxtSize, TextSizeType.FP);
            }
            btnPositive.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    if(bean.type == DefaultConfig.TYPE_MD_INPUT){
                        MdInputHolder holder = (MdInputHolder) bean.viewHolder;
                        boolean isvalid = bean.listener.onInputValid(holder.getTxt1(),holder.getTxt2(),holder.getEt1(),holder.getEt2());
                        if(isvalid){
                            bean.listener.onGetInput(holder.getTxt1(),holder.getTxt2());
                        }
                    }else if(bean.type == DefaultConfig.TYPE_MD_MULTI_CHOOSE){
                        bean.listener.onGetChoose(bean.checkedItems);
                        List<Integer> selectedIndex = new ArrayList<Integer>();
                        List<CharSequence> selectedStrs = new ArrayList<CharSequence>();
                        for(int j=0;j<bean.checkedItems.length;j++){
                            if(bean.checkedItems[j]){
                                selectedIndex.add(j);
                                selectedStrs.add(bean.wordsMd[j]);
                            }
                        }
                        bean.listener.onChoosen(selectedIndex,selectedStrs,bean.checkedItems);
                    }
                    bean.listener.onFirst();
                    dismiss(bean,true);
                }
            });
        }
        if(btnNegative !=null){
            if(!isEmpty(bean.text2)){
                btnNegative.setText(bean.text2.toString());
            }
            if (bean.btn2Color > 0 ){
                if(bean.btn2Color == DefaultConfig.iosBtnColor ){
                    setTextColorById(btnNegative, ResourceTable.Color_dialogutil_text_gray);
                }else {
                    setTextColorById(btnNegative, bean.btn2Color);
                }
            }


            if(bean.btnTxtSize >0){
                btnNegative.setTextSize(bean.btnTxtSize, TextSizeType.FP);
            }
        }

        if(btnNatural !=null){
            if(!isEmpty(bean.text3)){
                btnNatural.setText(bean.text3.toString());
            }
            if (bean.btn3Color > 0){
                setTextColorById(btnNatural, bean.btn3Color);
            }

            if(bean.btnTxtSize >0){
                btnNatural.setTextSize(bean.btnTxtSize, TextSizeType.FP);
            }
        }

    }

    public static ConfigBean fixContext(ConfigBean bean){
        AbilityContext activity1 = null;

        if(!(bean.context instanceof  Ability)){
            Ability activity = ActivityStackManager.getInstance().getTopActivity();
            if(isUsable(activity)){
                activity1 = activity;

            }
        }else {
            Ability activity = (Ability) bean.context;
            if(isUsable(activity)){
                activity1 = activity;
            }
        }
        if(activity1 !=null){
            bean.context = activity1;
        }else {
            bean.context = StyledDialog.context;
        }
        HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00102, "tool");
        HiLog.error(label, "fixContext:"+bean.context);
        return bean;
    }

    public static boolean isUsable(Ability activity) {
        if(activity ==null){
            return false;
        }

        if(activity.isTerminating()){
            return false;
        }

        return true;
    }


    /**
     * ViewRootImpl.checkThread:只有创建View层次结构的线程才能修改View
     * 如何保证new Dialog在UI线程执行?或者说,保证构建dialog view的线程和dismiss在同一线程?
     * 查看源码知道,dismiss回强制在UI线程,所以,构建dialogview的线程也必须是UI线程.
     * 什么时候构建dialog的viewroot?
     * 普通dialog: new Dialog()方法中: Window w = new PhoneWindow(mContext)
     * alertdialog: dialogbuilder.build()方法中
     *
     * @param bean
     * @return
     */
    public static ConfigBean newCustomDialog(ConfigBean bean){
        CustomDialog dialog = new CustomDialog(bean.context);
        dialog.setOnShowListener(new AlertDialog.OnShowListener() {
            @Override
            public void onShow() {
                Tool.adjustWH(dialog, bean);
            }
        });
        bean.dialog = dialog;
        return bean;
    }

    public static ConfigBean setCancelable(ConfigBean bean){
        if (bean.alertDialog != null){
            bean.alertDialog.siteRemovable(bean.cancelable);
            bean.alertDialog.setAutoClosable(bean.outsideTouchable);
        }else if (bean.dialog != null){
            bean.dialog.siteRemovable(bean.cancelable);
            bean.dialog.setAutoClosable(bean.outsideTouchable);
        }
        return bean;
    }







    public static void adjustStyle(final ConfigBean bean) {

        setBg(bean);
        setDim(bean);
        CommonDialog dialog = bean.dialog ==null ? bean.alertDialog : bean.dialog;
        Window window = dialog.getWindow();
        window.setLayoutAlignment(bean.gravity);
        if((bean.context instanceof AbilitySlice || bean.context instanceof Ability)){
            //setHomeKeyListener(window,bean);
        }else {
            window.addWindowFlags(WindowManager.LayoutConfig.MOD_TOAST);
            WindowManager.LayoutConfig params = window.getLayoutConfig().get();
            if(params==null){
                params = new WindowManager.LayoutConfig();
                params.height = ComponentContainer.LayoutConfig.MATCH_CONTENT;
                params.width = ComponentContainer.LayoutConfig.MATCH_CONTENT;
            }
            params.flags =
                    WindowManager.LayoutConfig.MARK_LOCAL_FOCUS_MODE  |
                            WindowManager.LayoutConfig.MARK_WATCH_OUTSIDE_TOUCH |
                            WindowManager.LayoutConfig.MOD_KEYGUARD; // TODO FLAG_DISMISS_KEYGUARD
            params.dim = 0.2f;

            window.setLayoutConfig(params);

            // back key pressed
            dialog.siteKeyboardCallback(new IDialog.KeyboardCallback() {

                @Override
                public boolean clickKey(IDialog iDialog, KeyEvent keyEvent) {
                    if (keyEvent.getKeyCode() == KeyEvent.KEY_BACK) {// TODO || keyEvent.getKeyCode() == KeyEvent.KEY_SETTINGS) {
                        StyledDialog.dismiss(bean.alertDialog,bean.dialog);
                        return true;
                    }
                    return false;
                }
            });

        }

    }



    private static void setDim(ConfigBean bean) {
        if(bean.type == DefaultConfig.TYPE_IOS_LOADING){//转菊花,则让背景透明
            bean.isTransparentBehind = true;
        }
        Window window = null;
        if (bean.alertDialog!= null){
            if(bean.isTransparentBehind){
                window = bean.alertDialog.getWindow();
            }
        }else {
            if(bean.isTransparentBehind){
                window = bean.dialog.getWindow();
            }
        }
        if (window != null)
        {
            WindowManager.LayoutConfig params = window.getLayoutConfig().get();
            if(params==null){
                params = new WindowManager.LayoutConfig();
            }
            params.dim = 0f;
            window.setLayoutConfig(params);
        }

    }

    /**
     * set background of dialog window
     * @param bean
     */
    private static void setBg(ConfigBean bean) {
//no need to modify the background
        if((bean.type == DefaultConfig.TYPE_BOTTOM_SHEET_GRID && bean.hasBehaviour)
                || bean.type == DefaultConfig.TYPE_BOTTOM_SHEET_LIST
                || bean.type == DefaultConfig.TYPE_BOTTOM_SHEET_CUSTOM
                || bean.type == DefaultConfig.TYPE_PROGRESS){
            // No need to set backgroud
            return;

        }


        if (bean.alertDialog!= null){

            if(bean.useTheShadowBg){
                // not support layer-list
            }else {
                if(bean.bgRes>0)
                    bean.alertDialog.getContentCustomComponent().setBackground(new ShapeElement(bean.context, bean.bgRes));
                else {
                    Element bge = bean.alertDialog.getContentCustomComponent().getBackgroundElement();
                    if (bge != null) {
                        bge.setAlpha(0);
                        bean.alertDialog.getContentCustomComponent().setBackground(bge);
                    }
                }

            }
        }else {
            if(bean.type == DefaultConfig.TYPE_IOS_LOADING || bean.asAdXStyle){//转菊花时,背景透明
                bean.dialog.setTransparent(true);
            }else if((bean.type == DefaultConfig.TYPE_BOTTOM_SHEET_GRID && !bean.hasBehaviour)){
                ShapeElement bge = (ShapeElement)bean.dialog.getContentCustomComponent().getBackgroundElement();
                if (bge != null) {
                    bge.setAlpha(1);
                    bge.setRgbColor(new RgbColor(255, 255, 255));
                    bean.dialog.getContentCustomComponent().setBackground(bge);
                }
            }else {
                if(bean.useTheShadowBg){
                    // not support layer-list
                }else {
                    if(bean.bgRes>0)
                        bean.dialog.getContentCustomComponent().setBackground(new ShapeElement(bean.context, bean.bgRes));
                    else {
                        Element bge = bean.dialog.getContentCustomComponent().getBackgroundElement();
                        if (bge != null) {
                            bge.setAlpha(0);
                            bean.dialog.getContentCustomComponent().setBackground(bge);
                        }
                    }
                }
            }

        }


    }







    public static void adjustWH( CommonDialog dialog,  ConfigBean bean ) {
        if (dialog == null){
            return;
        }

        Component rootView = dialog.getContentCustomComponent();
        WindowManager.LayoutConfig wl = dialog.getWindow().getLayoutConfig().get();
        if(wl == null) {
            wl = new WindowManager.LayoutConfig();
        }
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(StyledDialog.context);
        DisplayAttributes attrs = display.get().getAttributes();
        int width = attrs.width;
        int height = attrs.height;
        int measuredHeight = rootView.getEstimatedHeight();

        float widthRatio = 0.85f;
        float heightRatio = 0f;
        if(bean.type ==DefaultConfig.TYPE_IOS_BOTTOM){
            widthRatio = 0.95f;
        }else if(bean.type ==DefaultConfig.TYPE_IOS_CENTER_LIST){
            widthRatio = 0.9f;
        }
        if(width > height){//宽屏
            widthRatio = 0.5f;
        }

        //set ratio as user has set
        if(bean.forceWidthPercent >0 && bean.forceWidthPercent <=1.0f){
            widthRatio = bean.forceWidthPercent;
        }
        if(measuredHeight > bean.maxHeightPercent * height){
            heightRatio = bean.maxHeightPercent;
        }
        if(bean.forceHeightPercent >0 && bean.forceHeightPercent <=1.0f){
            heightRatio = bean.forceHeightPercent;
        }

        if(istheTypeOfNotAdjust(bean)){

        }else {
            int dialogW = (int) (width * widthRatio);
            int dialogH = measuredHeight;
            wl.width = (int) (width * widthRatio);
            if(heightRatio>0){
                wl.height = (int) (height* heightRatio);
                dialogH = (int) (height* heightRatio);
            }

            if(bean.type == DefaultConfig.TYPE_BOTTOM_SHEET_GRID && !bean.hasBehaviour){
                wl.height =measuredHeight;
                dialogH = measuredHeight;
            }
            dialog.setSize(dialogW, dialogH);
        }
    }

    public static boolean istheTypeOfNotAdjust(ConfigBean bean) {
        switch (bean.type){
            case DefaultConfig.TYPE_IOS_LOADING:
            case DefaultConfig.TYPE_BOTTOM_SHEET_CUSTOM:
            case DefaultConfig.TYPE_BOTTOM_SHEET_LIST:
                return true;
            case DefaultConfig.TYPE_BOTTOM_SHEET_GRID:
                return bean.hasBehaviour;
            default:
                return false;
        }
    }

    private static boolean isCustomType(ConfigBean bean) {
        switch (bean.type){
            case DefaultConfig.TYPE_IOS_HORIZONTAL:
            case DefaultConfig.TYPE_IOS_VERTICAL:
            case DefaultConfig.TYPE_IOS_BOTTOM:
            case DefaultConfig.TYPE_IOS_CENTER_LIST:
            case DefaultConfig.TYPE_IOS_INPUT:
            case DefaultConfig.TYPE_CUSTOM_VIEW:
            case DefaultConfig.TYPE_MD_LOADING:
            case DefaultConfig.TYPE_MD_ALERT:
            case DefaultConfig.TYPE_MD_MULTI_CHOOSE:
            case DefaultConfig.TYPE_MD_SINGLE_CHOOSE:
                return true;
            default:
                return false;
        }
    }


    public static void measureView(Component child) {
        ComponentContainer.LayoutConfig p = child.getLayoutConfig();
        if (p == null) {
            p = new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT
                    ,
                    ComponentContainer.LayoutConfig.MATCH_CONTENT);
        }
        int lpHeight = p.height;
        int lpWidth = p.width;
        int childHeightSpec;
        int childWidthSpec;
        if (lpHeight > 0) {   //如果Height是一个定值，那么我们测量的时候就使用这个定值
            childHeightSpec = Component.MeasureSpec.getMeasureSpec(lpHeight,
                    Component.MeasureSpec.PRECISE);
        } else {  // 否则，我们将mode设置为不指定，size设置为0
            childHeightSpec = Component.MeasureSpec.getMeasureSpec(0,
                    Component.MeasureSpec.UNCONSTRAINT);
        }
        if (lpWidth > 0) {
            childWidthSpec= Component.MeasureSpec.getMeasureSpec(lpHeight,
                    Component.MeasureSpec.PRECISE);
        } else {
            childWidthSpec= Component.MeasureSpec.getMeasureSpec(0,
                    Component.MeasureSpec.UNCONSTRAINT);
        }
        child.estimateSize(childWidthSpec, childHeightSpec);
    }

    /**
     *
     * @param root
     * @param id  height为0,weight为1的scrollview包裹的view的id,如果没有,传0或负数即可
     * @return
     */
    public static int mesureHeight(Component root, int id) {
        measureView(root);
        int height = root.getEstimatedHeight();
        int heightExtra = 0;
        if (id > 0){
            Component view = root.findComponentById(id);
            if (view != null){
                measureView(view);
                heightExtra = view.getEstimatedHeight();
            }

        }
        return height + heightExtra;
    }

    public static int mesureHeight(Component root, Component... subViews) {
        measureView(root);
        int height = root.getEstimatedHeight();
        int heightExtra = 0;
        if (subViews != null && subViews.length>0){
            for (Component view : subViews){
                if(view != null && view.getVisibility() == Component.VISIBLE){//确保设置了gone的view不再出现
                    measureView(view);
                    heightExtra += view.getEstimatedHeight();
                }

            }

        }

        return height + heightExtra;
    }

    public static int getColor(Context context,int colorRes){
        try {
            return context.getResourceManager().getElement(colorRes).getColor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static boolean isEmpty(CharSequence str)
    {
        return str == null || str.length() == 0;
    }


    public static void handleScrollInBottomSheetDialog(final ComponentContainer listView){
        listView.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component v, TouchEvent event) {
                // not support requestDisallowInterceptTouchEvent
                return false;
            }
        });
    }



    public static void showKeyBoard(Component edCount){
        //设置可获得焦点
        edCount.setFocusable(Component.FOCUS_ENABLE);
        edCount.setTouchFocusable(true);
        //请求获得焦点
        edCount.requestFocus();

        //调用系统输入法
        edCount.simulateClick();
    }

    public static void hideKeyBorad(ConfigBean bean){
        if(!bean.needSoftKeyboard){
            return;
        }
        if(bean.viewHolder !=null){
            bean.viewHolder.hideKeyBoard();
        }
        if(bean.customContentHolder !=null){
            bean.customContentHolder.hideKeyBoard();
        }
    }



    public static void hideKeyBoard(Text view){
        view.simulateClick();
    }
    public static void hideKeyBoard(Window window){
    }


    public static void removeFromParent(Component customView) {
        ComponentParent parent =  customView.getComponentParent();
        if(parent !=null){
            parent.removeComponent(customView);
        }
    }
    public static void setTextColorById(Text comp, int id)
    {
        Color ret = Color.BLACK;
        int color = Tool.getColor(comp.getContext(), id);
        ret = new Color(color);
        comp.setTextColor(ret);
    }
    public static void adjustSize(CommonDialog dialog, ConfigBean bean) {
        Component rootView = dialog.getContentCustomComponent();
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(StyledDialog.context);
        DisplayAttributes attrs = display.get().getAttributes();
        int width = attrs.width;
        int height = attrs.height;
        int measuredHeight = rootView.getHeight();
        int measuredWidth = rootView.getWidth();
        if (measuredHeight == 0)
        {
            measuredHeight = rootView.getEstimatedHeight();
        }
        if (measuredWidth == 0)
        {
            measuredWidth = rootView.getEstimatedWidth();
        }
        float widthRatio = 0f;
        float heightRatio = 0f;
        if(width > height){//宽屏
            widthRatio = 0.5f;
        }

        //set ratio as user has set
        if(bean.maxWidthPercent > 0 && measuredWidth > bean.maxWidthPercent * width){
            widthRatio = bean.maxWidthPercent;
        }
        if(bean.forceWidthPercent >0 && bean.forceWidthPercent <=1.0f){
            widthRatio = bean.forceWidthPercent;
        }
        if(bean.maxHeightPercent> 0 && measuredHeight > bean.maxHeightPercent * height){
            heightRatio = bean.maxHeightPercent;
        }
        if(bean.forceHeightPercent >0 && bean.forceHeightPercent <=1.0f){
            heightRatio = bean.forceHeightPercent;
        }

        boolean needUpdate = false;
        int dialogW = measuredWidth;
        int dialogH = measuredHeight;
        if(widthRatio >0){
            dialogW = (int) (width * widthRatio);//stretch when the content is not enough,margin when the content is full fill the screen
            needUpdate = true;
        }

        //only work when the content is full fill the screen
        if(heightRatio>0){
            dialogH = (int) (height* heightRatio);
            needUpdate = true;
        }
        dialog.setSize(dialogW, dialogH);

    }
}
